<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/11 0011
 * Time: 上午 10:35
 */
namespace App\Http\Admin\Plate\Controllers;

use Framework\BaseClass\Http\Admin\Controller;
use App\Http\Admin\Website\Models\Menu;
use App\Eloquent\Ygt\Plate;
use App\Eloquent\Ygt\Customer;
use App\Engine\Func;
use Illuminate\Support\Str;
use App\Eloquent\Ygt\ImgUpload;
use Illuminate\Support\Facades\Storage;

class IndexController extends Controller
{
    protected $modelName = 'Plate';
    protected $company = true;

    protected $rules = [
        'plate_name' => 'bail|required',
        'plate_no' => 'bail|required',
        'customer_id' => 'bail|required|integer',
        'sort_id' => 'required',
        'warning_days' => 'required|integer',
        'img_id' => 'required|integer',
    ];

    public function __construct()
    {
        parent::__construct();
        $this->model = new Plate();

    }

    protected function _hdata($result){
        $result->transform(function ($item, $key) {
            $item->img_url = Func::getImgUrlById($item->img_id);
            $item->customer_name = isset($item->customer->customer_name)?$item->customer->customer_name:'';
            $item->last_time = date('Y-m-d',$item->last_time);
            $categoryInfo = Plate::getCategory($item->category_id);
            $item->category_name = $categoryInfo['title'];
            return $item;
        });
        return $result;
    }

    protected function _honedata($info){
        $info->img_url = Func::getImgUrlById($info->img_id);
        $info->customer_name = isset($info->customer->customer_name)?$info->customer->customer_name:'';
        return $info;
    }

    protected function _where(){

        $where = [];
        if($customerName = request('plate_name')){
            $where['plate_name'] = ['like','%'.$customerName.'%'];
        }
        if($customerId = request('customer_id')){
            $where['customer_id'] = $customerId;
        }
        return $where;
    }

    protected function _export_title(){
        return [
            'plate_name'=>'版名称',
            'sort_id'=>'排序',
        ];
    }

    protected function _vdataAdd()
    {
        $categorys = Plate::getCategory();
        return [
            'category'=>$categorys
        ];
    }

    protected function _orderby(){
        return ['sort_id','desc'];
    }

    public function import(){
        if (request()->isMethod('post')) {
            if(request()->hasFile('upfile')){
                $path = request()->file('upfile')->path();
                $res = [];
                $excel = \Excel::load($path, function($reader) use( &$res ) {
                    $reader = $reader->getSheet(0);
                    $images = $reader->getDrawingCollection();
                    $res = $reader->toArray();
                    foreach ($images as $img){

                        $fileExtension = \File::extension($img->getIndexedFilename());

//                        dd($img->getRenderingFunction());

                        $xy = $img->getCoordinates();
//                        $coordinate = $reader->coordinateFromString($xy);
//                        dd($coordinate);

                        $preg    = '/(\d+)/i';
                        preg_match($preg, $xy, $matchs);
                        $y = $matchs[0];

                        $preg    = '/(\D+)/i';
                        preg_match($preg, $xy, $matchs);
                        $x = $matchs[0];
                        $fieldName = ($reader->getCell($x.'1')->getCalculatedValue());
                        if($fieldName == 'img_id'){
                            $type = 0;
                            $fileDir               = Func::getImgUploadConfig( 'file_dir', $type );
//                            dd(public_path('storage/'.$fileDir));
                            $filename = Str::random(40).'.'.$fileExtension;
                            $uploadPath = storage_path('upload/'.$fileDir.'/'.$filename);
                            $filePath = $fileDir.'/'.$filename;

                            $cimg = \Image::make($img->getImageResource());
                            $cimg->save($uploadPath);

                            $data               = [ 'type'=>$type, 'img_dir'=>$fileDir, 'img_url'=>$filePath ];
                            $insertId          = ImgUpload::insertOneData( $data, 'id' );

                            $col = 0;
                            $letters = (str_split($x));
                            foreach ($letters as $key => $value) {
                                $ascii = ord($value);
                                $col += $ascii%65+$key*26;
                            }
                            $row = $y-1;
                            $res[$row][$col] = $insertId;

                        }
                    }
                });
                $excel->store('xls',storage_path('upload/plate/error_import_data/'));

                $fields = $res[0];
                $titles = $res[1];
                $importData = [];
                $failData = [];
                foreach ($res as $key=>$val){
                    if($key<2)continue;
                    $tmp = [];
                    $lineResult = true;
                    foreach ($fields as $col=>$field){
                        switch ($field){
                            case 'category_name':
                                $categoryName = $val[$col];
                                $categorys = collect(Plate::getCategory());
                                $categoryId = $categorys->search(function($value, $key) use($categoryName){
                                    return $value['title'] == $categoryName;
                                });
                                if($categoryId){
                                    $tmp['category_id'] = $categoryId;
                                }else{
                                    $tmp['category_name'] = '<<'.$val[$col].'>>';
                                    $lineResult = false;
                                }
                                break;
                            case 'customer_name':
                                $customerInfo = Customer::where('customer_name',$val[$col])->first();
                                if($customerInfo){
                                    $tmp['customer_id'] = $customerInfo['id'];
                                }else{
                                    $tmp['customer_name'] = '<<'.$val[$col].'>>';
                                    $lineResult = false;
                                }
                                break;
                            default:
                                $tmp[$field] = $val[$col];
                                break;
                        }

                    }
                    if($lineResult === false){
                        $failData[] = $tmp;
                    }else{
                        $adminUser = request()->user('admin')->toArray();
                        $company_id = $adminUser['company_id'];
                        $tmp['company_id'] = $company_id;
                        $importData[] = $tmp;
                    }
                }
                if($failData){
//                    return $this->ajaxFail($failData);
                    $failFileNmae = Str::random(20);
                    \Excel::create(iconv('UTF-8','gbk',$failFileNmae),function($excel) use ($failData){
                        $excel->sheet('score', function($sheet) use ($failData){
                            $sheet->rows($failData);
                        });
                    })->store('xls',storage_path('upload/plate/error_import_data/'));
                    if(request('error_type') == 2){
                        return $this->ajaxFail('数据有误<a href="'.Storage::url('/plate/error_import_data/'.$failFileNmae.'.xls').'">查看</a>');
                    }
                }
                $this->model->insertData($importData);

                return $this->ajaxSuccess('成功'.count($importData).'失败'.count($failData).'<a href="'.Storage::url('/plate/error_import_data/'.$failFileNmae.'.xls').'">查看</a>');

            }else{
                return $this->ajaxFail();
            }
        }

        return $this->view('import');
    }
}